export function useStorage<T>(key: string) {
  function init(value: Partial<T>) {
    const storage = uni.getStorageSync(key);
    if (!storage) {
      setAll(value);
    }
  }

  function getAll() {
    const storage = uni.getStorageSync(key);
    const parse = JSON.parse(storage);
    return parse;
  }

  function setAll(value: Partial<T>) {
    try {
      const stringify = JSON.stringify(value);
      uni.setStorageSync(key, stringify);
    } catch (error) {
      uni.showToast({ title: "存储失败", icon: "none" });
    }
  }

  function getValue(property: keyof T) {
    const storage = uni.getStorageSync(key);
    const parse = JSON.parse(storage);
    return get(parse, property);
  }

  function setValue(key: keyof T, value: T[keyof T]) {
    try {
      const data = getAll();
      set(data, key, value);
      setAll(data);
    } catch (error) {
      console.log(error, "error");
      uni.showToast({ title: "存储失败", icon: "none" });
    }
  }

  return {
    init,
    getAll,
    setAll,
    getValue,
    setValue,
  };
}
